<?php
/**
 * 借款申请管理
 */
namespace Admin\Controller\Borrow;
use Think\Controller;
use Admin\Controller\Common\BaseController;
use Admin\Controller\Common\SendMessageController;

class BorrowapplyController extends BaseController
{
	/**
	 *	管理后台菜单初始化与用户登录身份验证
	 */
//	public function _initialize()
//	{
//		session('facId','51');
//		// 判断用户是否登陆
//		if (!session('?facId'))
//		{
//			$url = 'http://' . $_SERVER['HTTP_HOST'] .'/tp_bypal/index.php';
//			redirect($url);
//			exit;
//		}
//	}


	/**
	 *	借款申请列表页
	 */
	public function borrowapply_list() 
	{


		//	申请状态下拉框数据
		$model_state = M('bypal_cust_loanstatus');
		$array_state = $model_state->select();
		$this->assign('array_state',$array_state);

		$this->display();
	}

    public function borrowapply_main(){
        $page=I("post.page","1");
        $rows=I("post.rows","10");
        $select_borrowNum = I("post.select_borrowNum","");
        $select_custName = I("post.select_custName","");
        $select_businessName = I("post.select_businessName","");
        $select_checkState = I("post.select_checkState","");
        $select_start_time = I("post.select_start_time","");
        $select_end_time = I("post.select_end_time","");

        $search_array['select_borrowNum'] = $select_borrowNum;
        $search_array['select_custName'] = $select_custName;
        $search_array['select_businessName'] = $select_businessName;
        $search_array['select_checkState'] = $select_checkState;
        $search_array['select_start_time'] = $select_start_time;
        $search_array['select_end_time'] = $select_end_time;

        $this->assign("search_array",$search_array);

        $borrowinfo = D('Borrowinfo');
        $borrow_array=$borrowinfo->borrow_apply($search_array,$page,$rows);
        $count=$borrowinfo->borrow_apply_count($search_array);
        $result['total']=$count;
        $result['rows']=$borrow_array;
        $json_list = json_encode($result);
        echo $json_list;
    }


	/**
	 *	借款申请列表页#####取消操作
	 */
	public function borrowapply_cancel() 
	{
		if ($_POST && array_key_exists('borrow_id', $_POST) && $_POST['borrow_id']) 
		{
			$model_borrow_info = M('bypal_borrow_info');
			$update_borrow_info['borrow_stateid'] = '4';

			$model_facilitator_trade = M('bypal_facilitator_trade');
			$update_facilitator_trade['tid'] = '8';
			$update_facilitator_trade['trade_cancelask_time'] = time();
			$update_facilitator_trade['trade_canclereason'] = $_POST['content'];
			if ($model_borrow_info->where('borrow_id="'.$_POST['borrow_id'].'"')->save($update_borrow_info) && $model_facilitator_trade->where('trade_contractnumber="'.$_POST['borrow_id'].'"')->save($update_facilitator_trade)) 
			{
				$result['state'] = '1';
				$result['message'] = "取消成功！";
			}
			else
			{
				$result['state'] = '1';
				$result['message'] = "取消失败，请稍后重试！";
			}

			$this->ajaxReturn(json_encode($result));
		}
	}


	/**
	 *	借款申请详情
	 */
	public function borrowapply_detail() 
	{
//		if (IS_GET && I('get.borrow_id'))
//		{
//			$model = M('bypal_borrow_info');
//			$data_borrowInfo = $model->where('borrow_id='.I('get.borrow_id'))->find();
//
//			//	借款申请状态
//			$model_loanstatus = M('bypal_cust_loanstatus');
//			$data_loanstatus = $model_loanstatus->where('ls_id='.$data_borrowInfo['borrow_stateid'])->find();
//			$data_borrowInfo['ls_value'] = $data_loanstatus['ls_value'];
//
//			//	商户全称
//			$model_facilitatorInfo = M('bypal_facilitator_info');
//			$data_facilitatorInfo = $model_facilitatorInfo->where('id='.$data_borrowInfo['borrow_busid'])->find();
//			$data_borrowInfo['fac_name'] = $data_facilitatorInfo['fac_name'];
//
//			//	利率计算方式
//			$data_borrowInfo['fac_rate_method'] = $data_facilitatorInfo['fac_rate_method'];
//
//			//	商户联系人
//			$data_borrowInfo['fac_contact'] = $data_facilitatorInfo['fac_contact'];
//
//			//	商户联系电话
//			$data_borrowInfo['fac_contactphone'] = $data_facilitatorInfo['fac_contactphone'];
//
//			//	商户类别
//			$model_management_type = M('bypal_management_type');
//			$data_management_type = $model_management_type->where('man_type_id='.$data_facilitatorInfo['man_type_id'])->find();
//			$data_borrowInfo['man_type'] = $data_management_type['man_type'];
//
//			//	服务分类
//			$model_facilitator_itype = M('bypal_facilitator_itype');
//			$data_facilitator_itype = $model_facilitator_itype->where('trade_number="'.$data_facilitatorInfo['fac_separatetype'].'"')->find();
//			$data_borrowInfo['service_type'] = $data_facilitator_itype['name'];
//
//			//	审核未过原因
//			$model_freason = M('bypal_borrow_freason');
//			$data_freason = $model_freason->where('f_id='.$data_borrowInfo['borrow_freson'])->find();
//			$data_borrowInfo['f_value'] = $data_freason['f_value'];
//
//			//	备注
//			$model_cust_reference = M('bypal_cust_reference');
//			$condition['ref_custid'] = $data_borrowInfo['borrow_custid'];
//			$condition['ref_type'] = array('in', '1,2');
//			if ($data_cust_reference = $model_cust_reference->where($condition)->find())
//			{
//				if ($data_cust_reference['ref_status'] == '1')
//				{
//					$data_borrowInfo['remark'] = '身份证审核已通过';
//				}
//				else
//				{
//					$data_borrowInfo['remark'] = '身份证审核未通过';
//				}
//			}
//			else
//			{
//				$data_borrowInfo['remark'] = '身份证未上传';
//			}
//
//			//	首付金额
//			$model_facilitator_trade = M('bypal_facilitator_trade');
//			$data_facilitator_trade = $model_facilitator_trade->where('trade_contractnumber='.$data_borrowInfo['borrow_id'])->find();
//			$data_borrowInfo['fac_payment'] = $data_facilitator_trade['fac_payment'];
//
//			//	延期月数
//			$data_borrowInfo['delay_time'] = $data_facilitator_trade['delay_time'];
//
//			//	员工姓名
//			$model_facilitator_person = M('bypal_facilitator_person');
//			$data_facilitator_person = $model_facilitator_person->where('facp_workid='.$data_facilitator_trade['trade_pernumber'])->find();
//			$data_borrowInfo['facp_name'] = $data_facilitator_person['facp_name'];
//
//			//	员工电话
//			$data_borrowInfo['facp_phone'] = $data_facilitator_person['facp_phone'];
//
//			//	员工邮箱
//			$data_borrowInfo['facp_loginname'] = $data_facilitator_person['facp_loginname'];
//
//			//	同盾返回结果
//			$model_impl_fm = M('bypal_impl_fm');
//			$data_impl_fm = $model_impl_fm->where('code='.$data_borrowInfo['borrow_id'])->find();
//			$data_borrowInfo['fm_result'] = $data_impl_fm['fm_result'];
//
//			//	借款等级
//			$model_borrow_adjustvalue = M('bypal_borrow_adjustvalue');
//			$data_borrow_adjustvalue = $model_borrow_adjustvalue->where('ad_id='.$data_borrowInfo['borrow_level'])->find();
//			$data_borrowInfo['ad_level'] = $data_borrow_adjustvalue['ad_level'];
//
//			//	安融信用得分
//			$model_impl_countcredit = M('bypal_impl_countcredit');
//			$data_impl_countcredit = $model_impl_countcredit->where('applyId='.$data_borrowInfo['borrow_id'])->find();
//			$data_borrowInfo['anrong_scrore'] = $data_impl_countcredit['count'];
//
//			//	借款用途
//			$model_cust_loantype = M('bypal_cust_loantype');
//			$data_cust_loantype = $model_cust_loantype->where('lt_id='.$data_borrowInfo['borrow_applyid'])->find();
//			$data_borrowInfo['lt_value'] = $data_cust_loantype['lt_value'];
//
//			//	剩余分期额度
//			$array_data1 = $model->where('borrow_custid='.$data_borrowInfo['borrow_custid'])->select();
//			$array_exist = array();
//			foreach ($array_data1 as $k => $val)
//			{
//				array_push($array_exist, $val['borrow_id']);
//			}
//			$condition1['binfo_id'] = array('in', $array_exist);
//			$condition1['repay_date'] = '0';
//			$model_repayDetail = M('bypal_repay_detail');
//			$sum = $model_repayDetail->where($condition1)->sum('principal');
//			$data_borrowInfo['sum'] = round(50000-$sum,2);
//
//			//	还款方式
//			$model_repay_method = M('bypal_repay_method');
//			$data_repay_method = $model_repay_method->where('repay_id='.$data_borrowInfo['borrow_repayid'])->find();
//			$data_borrowInfo['repay_name'] = $data_repay_method['repay_name'];
//
//			//	客户姓名
//			$model_cust_info = M('bypal_cust_info');
//			$data_cust_info = $model_cust_info->where('cust_id='.$data_borrowInfo['borrow_custid'])->find();
//			$data_borrowInfo['cust_name'] = $data_cust_info['cust_name'];
//
//			//	客户电话
//			$data_borrowInfo['cust_phone'] = $data_cust_info['cust_phone'];
//
//			$this->assign('data_borrowInfo',$data_borrowInfo);
//
//			$this->display();
//		}
//		else
//		{
//			echo "<script>alert('地址错误，请正确操作！');history.back();</script>";
//			exit;
//		}

        if(IS_GET&&I("get.borrow_id",'','/^\d+$/')!=''){
            $borrow_id=I("get.borrow_id");
//            $borrowinfo=D("Borrowinfo");
//            $borrow_array=$borrowinfo->borrow_info_detail($borrow_id);

//            $this->assign("borrow_array",$borrow_array);
//            $this->assign("borrow_json",json_encode($borrow_array));
            $this->assign("borrow_id",$borrow_id);
            $this->display();
        }else{
            $this->error('参数错误','/Article/error');
        }
	}

    public function ajax_borrow_detail(){
        if(IS_POST&&I("post.borrow_id",'','/^\d+$/')!=''){
            $borrow_id=I("post.borrow_id");
            $borrowinfo=D("Borrowinfo");
            $borrow_array=$borrowinfo->borrow_info_detail($borrow_id);
//            $result["borrow_array"]=$borrow_array;
            $this->ajaxReturn($borrow_array);
        }
    }

    public function ajax_supple_detail(){
        if(IS_POST&&I("post.borrow_id",'','/^\d+$/')!=''){
            $borrow_id=I("post.borrow_id");
            $borrowinfo=D("Borrowinfo");
            $supple_array=$borrowinfo->borrow_supple_detail($borrow_id);
            $this->ajaxReturn($supple_array);
        }
    }

    public function ajax_remark_table(){
        if(IS_POST&&I("post.borrow_id",'','/^\d+$/')!=''){
            $borrow_id=I("post.borrow_id");
            $BorrowRemark=D("BorrowRemark");
            $remark_array=$BorrowRemark->select_remark_list($borrow_id);
            $this->ajaxReturn(json_encode($remark_array));
        }
    }


	/**
	 *	借款申请详情#####修改借款金额
	 */
	public function borrowapply_detail_updateMoney() 
	{
		if (IS_GET && I('get.type') && I('get.type') == 'updateMoney') 
		{
			$model = M('bypal_borrow_info');
			$model->borrow_money = I('get.money');

			$model_facilitator_trade = M('bypal_facilitator_trade');
			$data_facilitator_trade = $model_facilitator_trade->where('trade_contractnumber='.I('get.borrow_id'))->find();
			$model_facilitator_trade->fac_payment = $data_facilitator_trade['trade_allmoney'] - I('get.money');

			if ($model->where('borrow_id='.I('get.borrow_id'))->save() && $model_facilitator_trade->where('trade_contractnumber='.I('get.borrow_id'))->save()) 
			{
				$result['state'] = 1;
				$result['message'] = "修改成功";
			}
			else
			{
				$result['state'] = 2;
				$result['message'] = "修改失败";
			}
		}
		else
		{
			$result['state'] = 2;
			$result['message'] = "修改失败";
		}

		$this->ajaxReturn(json_encode($result));
	}


	/**
	 *	借款申请详情#####同盾返回结果查看
	 */
	public function borrowapply_detail_tongdunResult() 
	{
		if ($_POST && $_POST['borrow_id']) 
		{
			$model = M('bypal_impl_fm');
			$array_data = $model->where('code='.$_POST['borrow_id'])->select();
			$array_id = array('0');
			foreach ($array_data as $key => $value) 
			{
				array_push($array_id, $value['fm_id']);
			}

			$model_impl_fmrules = M('bypal_impl_fmrules');
			$condition['fm_id'] = array('in', $array_id);
			$array_impl_fmrules = $model_impl_fmrules->where($condition)->select();
			
			$result = "<table class='list' cellspacing='0' cellpadding='0'>";
			$result .= "<thead>";
			$result .= "<tr>";
			$result .= "<th>结果</th>";
			$result .= "<th>规则名称</th>";
			$result .= "<th>得分</th>";
			$result .= "</tr>";
			$result .= "<thead>";
			$result .= "<tbody>";
			foreach ($array_impl_fmrules as $key => $value) 
			{
				$result .= "<tr>";
				$result .= "<td><input type='text' value='".$value['decision']."' ></td>";
				$result .= "<td><input type='text' value='".$value['rules_name']."' ></td>";
				$result .= "<td><input type='text' value='".$value['score']."' ></td>";
				$result .= "</tr>";
			}
			$result .= "</tbody>";
			$result .= "</table>";

			$this->ajaxReturn($result);
		}
	}


	/**
	 *	借款申请详情#####修改利率
	 */
	public function borrowapply_detail_updateRate() 
	{
		if (IS_GET && I('get.borrow_id') && I('get.rate')) 
		{
			$model = M('bypal_borrow_info');
			$model->borrow_rate = I('get.rate');

			$model_facilitator_trade = M('bypal_facilitator_trade');
			$model_facilitator_trade->trade_rate = I('get.rate');

			if ($model->where('borrow_id='.I('get.borrow_id'))->save() && $model_facilitator_trade->where('trade_contractnumber='.I('get.borrow_id'))->save()) 
			{
				$result['state'] = 1;
				$result['message'] = "修改成功";
			}
			else
			{
				$result['state'] = 2;
				$result['message'] = "修改失败";
			}
		}
		else
		{
			$result['state'] = 2;
			$result['message'] = "修改失败";
		}

		$this->ajaxReturn(json_encode($result));
	}


	/**
	 *	借款申请详情#####是否进入选择期限流程#####通过
	 */
	public function borrow_second_examine()
	{
        $borrow_id=I("post.borrow_id");
        $borrow_info=D("Borrowinfo");
        $borrow_array=$borrow_info->update_borrow_second_examine($borrow_id);
        if($borrow_array!=0){
            $cust_array=$borrow_info->borrow_cust_info($borrow_id);
            $send_message=new SendMessageController();
            $array=array(
                "0"=>array("custName",$cust_array['cust_name']),
                "1"=>array("money",$cust_array['borrow_money'])
            );
            $message=$send_message->short_message_context("0005",$array);
            $send_message->sendSMS($cust_array['cust_id'],$cust_array['cust_phone'],$message);
            $result['state']=1;
            $result['message']="复审通过";
        }else{
            $result['state']=2;
            $result['message']="操作失败";
        }
		$this->ajaxReturn($result);
	}


	/**
	 *	借款申请详情#####是否进入选择期限流程#####不通过
	 */
	public function borrow_reject_examine()
	{
        $borrow_id=I("post.borrow_id");
        $borrowinfo = D('Borrowinfo');
        $borrow_array=$borrowinfo->update_borrow_reject_examine($borrow_id,3);
        if ($borrow_array!=0)
        {
            $result['state'] = 1;
            $result['message'] = "操作成功";
        }
        else
        {
            $result['state'] = 2;
            $result['message'] = "操作失败";
        }

		$this->ajaxReturn($result);
	}

    public function borrow_cancel(){
        $borrow_id=I("post.borrow_id");

        $borrowinfo = D('Borrowinfo');
        $borrow_array=$borrowinfo->update_borrow_reject_examine($borrow_id,4);

        $cust_array=$borrowinfo->borrow_cust_info($borrow_id);
        $send_message=new SendMessageController();
        $array=array(
            "0"=>array("custName",$cust_array['cust_name']),
            "1"=>array("borrowTitle",$cust_array['borrow_title']),
            "2"=>array("borrowId",$borrow_id)
        );
        $message=$send_message->short_message_context("0044",$array);
        $send_message->sendSMS($cust_array['cust_id'],$cust_array['cust_phone'],$message);

        if ($borrow_array!=0)
        {
            $result['state'] = 1;
            $result['message'] = "操作成功";
        }
        else
        {
            $result['state'] = 2;
            $result['message'] = "操作失败";
        }
        $this->ajaxReturn($result);
    }

    public function file_zip(){
        $cust_id=I("post.cust_id");

        $arrfiles = array(); //这里是附件的文件数组

        $cust_reference=D("Custreference");
        $reference_files=$cust_reference->select_reference_bycust($cust_id);
        if(count($reference_files)>0) {
            foreach ($reference_files as $reference_file) {
                $arrfiles[]=C("reference_address").$reference_file['ref_annex'];
            }
            $downFileName = $cust_id . '.zip'; //下载的文件名 如果为空那么就是系统自定义名称 如果指定就显示指定名字
            $zipUrl = create_zip($arrfiles, $cust_id); //生成的压缩文件名词
            $result['state'] = 1;
            $result["message"] = "压缩成功";
            $result['zipUrl'] = $zipUrl;
        }else{
            $result['state']=2;
            $result['message']="没有数据";
        }
        $this->ajaxReturn($result);
    }

    public function select_borrow_period(){
        $borrow_id=I("post.borrow_id");

        $borrow_info=D("Borrowinfo");
        $period_array=$borrow_info->select_borrow_period($borrow_id);

        $this->ajaxReturn($period_array);
    }

    public function select_borrow_data(){
        $borrow_id=I("post.borrow_id");

        $borrow_info=D("Borrowinfo");
        $data_array=$borrow_info->select_borrow_data($borrow_id);

        $this->ajaxReturn($data_array);
    }

    public function subimit_borrow_period(){
        $borrow_id=I("post.borrow_id");
        $state=I("post.state");
        $borrow_period=I("post.borrow_period");
        $borrow_info=D("Borrowinfo");
        $borrow_info->cancel_borrow_period($borrow_id);
        if($state==2){
            $period_result=$borrow_info->insert_borrow_period($borrow_id,$borrow_period);
        }else{
            $period_result=$borrow_info->submit_borrow_period($borrow_id,$borrow_period);
        }
        if($period_result!=0){
            $result['state']=1;
            $result['message']="操作成功";
            $result['result']=$period_result;
        }else{
            $result['state']=2;
            $result['message']="操作失败";
            $result['result']=$period_result;
        }
        $this->ajaxReturn($result);
    }

    public function submit_borrow_data(){
        $datas=I("post.data");
        $borrow_id=I("post.borrow_id");
        $cust_id=I("post.cust_id");
        $borrow_info=D("Borrowinfo");
        foreach($datas as $data){
            $state=$data['state'];
            $checked=$data['checked'];
            $data_id=$data['id'];
            switch ($state) {
                case 1:
                    if($checked==0){
                        $borrow_info->update_borrow_data($borrow_id,$data_id,2);
                    }
                    break;
                case 2:
                    if($checked==1){
                        $borrow_info->update_borrow_data($borrow_id,$data_id,1);
                    }
                    break;
                case 0:
                    if($checked==1){
                        $borrow_info->update_borrow_data($borrow_id,$data_id,1);
                    }
                    break;
                case 4:
                    if($checked==1){
                        $borrow_info->insert_borrow_data($borrow_id,$cust_id,$data_id);
                    }
                    break;

            }
        }

        $borrow_info->update_borrow_state_fordata($borrow_id);

        $result['state']=1;
        $result['message']="审核资料操作成功";
        $this->ajaxReturn($result);
    }


	/**
	 *	借款申请详情#####同盾审核通过
	 */
//	public function borrowapply_detail_acceptFM()
//	{
//		if ($_POST && $_POST['borrow_id'] && $_POST['cust_id'])
//		{
//			$result['state'] = 1;
//			$result['message'] = "初审通过";
//
//			$this->ajaxReturn($result);
//		}
//	}
}